/**
 * Created by yinzhengfei on 2016/6/15.
 */
var Popup = {
    storageKeys:{
        sqlList:'switch-sql-log-list',
        defaultSqlLogKey:'default-sql-log-text'
    },
    subjects: {
        localStorage: 'localStorage',
        removeLocalStorage:'removeLocalStorage'
    },
    init: function () {
        $('#progress').hide();
        $('#content').show();
        Popup.sqlLogHandler();
        //初始化sql日志记录开关
        Popup.getSqlList(function (_data) {
            $('#isSqlLog').bootstrapSwitch({
                state:_data.switch?true:false
            }).on('switchChange.bootstrapSwitch', function (e) {
                _data.switch = e.target.checked;
                Popup.sendMsg(Popup.subjects.localStorage,{
                    name:Popup.storageKeys.sqlList,
                    value:JSON.stringify(_data)
                });
            });
        });
    },
    sqlLogHandler:function () {
        Popup.initSqlLogCreate();
        Popup.initSqlLogList();
    },
    initSqlLogCreate:function () {
        var $sqlList = $('#sql-log-lists'),
            $newBtn = $('#new-sql-item'),
            titleTem = $('#sql-log-list-new').html();
        $newBtn.click(function () {
            var dom = $(titleTem),
                text = dom.find('input');
            $sqlList.append(dom);
            dom.find('button[name="save"]').click(function () {
                if ($.trim(text.val()) === ''){
                    alert('标题不能为空');
                    return;
                }
                Popup.getSqlList(function (data) {
                    var list = data.list;
                    for(var i=0; i<list.length; i++){
                        if (list[i].name === $.trim(text.val())){
                            alert('标题已存在');
                            return;
                        }
                    }
                    data.current = Popup.guid();
                    data.list.push({
                        id:data.current,
                        name:text.val()
                    });
                    Popup.saveLogList(data,function () {
                        dom.remove();
                    });
                });
            });
            dom.find('button[name="cancel"]').click(function () {
                dom.remove();
            });
        });
    },
    initSqlLogList:function () {
        var $sqlList = $('#sql-log-lists'),
            sqlListItem = _.template($('#sql-log-list-item').html());
        $sqlList.empty();
        Popup.getSqlList(function (data) {
            var list = data.list,
                item;
            if (data.current == undefined){
                data.current = Popup.storageKeys.defaultSqlLogKey;
            }
            list.unshift({
                id:Popup.storageKeys.defaultSqlLogKey,
                name:"Default"
            });
            for (var i=0; i< list.length; i++){
                item = $(sqlListItem(list[i]));
                if (list[i].id === Popup.storageKeys.defaultSqlLogKey){
                    item.find('button').hide();
                }else{
                    item.find('button').click(function () {
                        var id = $(this).parent().find('label').attr('id');
                        Popup.getSqlList(function (data) {
                            if (data.current === id){
                                data.current = undefined;
                            }
                            for (var j=0; j<data.list.length;j++){
                                if (data.list[j].id === id){
                                    data.list.splice(j,j+1);
                                    break;
                                }
                            }
                            Popup.saveLogList(data,function () {
                                Popup.removeLog(id);
                            });
                        });
                    });
                }

                if (data.current === list[i].id){
                    item.addClass('active');
                }
                item.find('label').click(function () {
                    var id = $(this).attr('id');
                    Popup.getSqlList(function (data) {
                        data.current = id;
                        Popup.saveLogList(data);
                    });
                });
                $sqlList.append(item);
            }
        });
    },
    saveLogList:function (data, callback) {
        Popup.sendMsg(Popup.subjects.localStorage, {
            name: Popup.storageKeys.sqlList,
            value:JSON.stringify(data)
        },function () {
            Popup.initSqlLogList();
            chrome.tabs.reload();
            if (typeof callback === 'function')
                callback();
        });
    },
    removeLog:function (key,callback) {
        Popup.sendMsg(Popup.subjects.removeLocalStorage, {
            name: key
        },function () {
            if (typeof callback === 'function')
                callback();
        });
    },
    getSqlList:function (callback) {
        Popup.sendMsg(Popup.subjects.localStorage, {
            name: Popup.storageKeys.sqlList
        },function (data) {
            data = data[0];
            if (typeof callback !== 'function')
                return;
            if (data === undefined || data.value === undefined){
                callback({
                    current:Popup.storageKeys.defaultSqlLogKey,
                    list:[]
                });
            }else{
                callback(JSON.parse(data.value));
            }
        });
    },
    sendMsg: function (subject, data, successCallback) {
        chrome.extension.sendRequest(
            {type: subject, data: data},
            function (response) {
                if (typeof successCallback === 'function')
                    successCallback(arguments);
            });
    },
    guid:function (){
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    }
}

$(function () {
    Popup.init();
});